<template>
  <div class="question-selector-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-input
              v-model="queryParams.keyword"
              placeholder="搜索标题/内容"
              clearable
              @keyup.enter.native="handleQuery"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="handleQuery"
              />
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="queryParams.typeId"
              placeholder="选择题型"
              clearable
              @change="handleQuery"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="queryParams.difficult"
              placeholder="选择难度"
              clearable
              @change="handleQuery"
            >
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-button
              type="primary"
              @click="handleConfirm"
            >确认选择({{ selectedIds.length }})
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 分类树和内容区域 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="never">
            <div slot="header" class="clearfix">
              <span>分类筛选</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click="resetCategory"
              >重置
              </el-button>
            </div>
            <el-input
              v-model="categoryFilterText"
              placeholder="输入分类名称搜索"
              clearable
              prefix-icon="el-icon-search"
            />
            <el-tree
              ref="categoryTree"
              class="filter-tree"
              :data="categoryTree"
              :props="categoryProps"
              :filter-node-method="filterCategoryNode"
              node-key="id"
              highlight-current
              @node-click="handleCategoryNodeClick"
            />
          </el-card>
        </el-col>
        <el-col :span="18">
          <!-- 题目卡片列表 -->
          <div v-loading="loading">
            <el-row :gutter="20">
              <el-col
                v-for="item in questionList"
                :key="item.id"
                :span="24"
                class="mb-20"
              >
                <el-card class="question-card" shadow="hover">
                  <!-- 头部 -->
                  <div slot="header" class="clearfix header-area">
                    <el-checkbox
                      v-model="selectedIds"
                      :label="item.id"
                      @click.native.stop
                      class="question-checkbox"
                    ></el-checkbox>
                    <span
                      class="question-title"
                      @click.stop="toggleSelect(item.id)"
                      v-html="item.title"
                    />
                    <el-tag
                      v-if="item.type_name"
                      size="small"
                      style="float: right"
                    >{{ item.type_name }}
                    </el-tag>
                  </div>

                  <!-- 内容区域 -->
                  <div class="content-container" @click.stop="handleDetail(item)">
                    <formula-renderer class="question-content" v-if="item.content" :html="item.content" />
                  </div>

                  <!-- 难度评分 -->
                  <div class="difficulty-row">
                    <el-rate
                      v-model="item.difficult"
                      disabled
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900','#ff00bb', '#ff002f']"
                    />
                  </div>

                  <!-- 知识点标签区域 -->
                  <div class="tags-container">
                    <el-tag
                      v-for="cat in item.categories.split(',')"
                      :key="cat"
                      size="mini"
                      type="info"
                      class="tag-item"
                    >{{ cat }}
                    </el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 分页 -->
            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { listQuestion, fulltextSearch, listQuestionTypes } from '@/api/question2/question'
import { getCategoryTree } from '@/api/question2/category'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'QuestionSelector',
  components: {FormulaRenderer},
  props: {
    selectedQuestions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedIds: [...this.selectedQuestions],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined,
        typeId: undefined,
        difficult: undefined,
        categoryId: undefined
      },
      fulltextKeyword: undefined,
      // 题目列表
      questionList: [],
      total: 0,
      loading: true,
      // 分类树
      categoryTree: [],
      categoryProps: {
        label: 'name',
        children: 'children'
      },
      categoryFilterText: '',
      // 题型选项
      typeOptions: [],
      // 难度选项
      difficultyOptions: [
        { value: 1, label: '简单' },
        { value: 2, label: '偏易' },
        { value: 3, label: '中等' },
        { value: 4, label: '偏难' },
        { value: 5, label: '困难' }
      ]
    }
  },
  created() {
    this.getList()
    this.getCategoryTree()
    this.getTypeOptions()
  },
  watch: {
    categoryFilterText(val) {
      this.$refs.categoryTree.filter(val)
    },
    selectedQuestions(val) {
      this.selectedIds = [...val]
    }
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true
      listQuestion(this.queryParams).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 全文搜索 */
    handleFulltextSearch() {
      if (!this.fulltextKeyword) {
        this.$message.warning('请输入搜索关键词')
        return
      }

      this.loading = true
      fulltextSearch({
        keyword: this.fulltextKeyword,
        categoryId: this.queryParams.categoryId,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize
      }).then(response => {
        this.questionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取分类树 */
    getCategoryTree() {
      getCategoryTree().then(response => {
        this.categoryTree = response.data
      })
    },
    // 获取题型选项
    getTypeOptions() {
      listQuestionTypes().then(response => {
        this.typeOptions = response.data
      })
    },
    /** 分类树筛选 */
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    /** 分类节点点击事件 */
    handleCategoryNodeClick(data) {
      if (data.isKnowledge === 1) return
      this.queryParams.categoryId = data.id
      this.handleQuery()
    },
    /** 重置分类筛选 */
    resetCategory() {
      this.queryParams.categoryId = undefined
      this.$refs.categoryTree.setCurrentKey(null)
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 查看详情 */
    handleDetail(row) {
      this.$emit('detail', row)
    },
    // 切换选中状态
    toggleSelect(id) {
      const index = this.selectedIds.indexOf(id)
      if (index === -1) {
        this.selectedIds.push(id)
      } else {
        this.selectedIds.splice(index, 1)
      }
    },
    handleConfirm() {
      const selectedQuestions = this.questionList.filter(q =>
        this.selectedIds.includes(q.id))
      this.$emit('confirm', selectedQuestions)
    }
  }
}
</script>

<style lang="scss" scoped>
.question-card {
  position: relative;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;

  .header-area {
    display: flex;
    align-items: center;
    padding-right: 40px;
    flex-shrink: 0;
  }

  .content-container {
    flex: 1;
    min-height: 60px;
    margin: 10px 0;

    .question-content {
      max-height: 4.5em;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
      line-height: 1.5em;
      cursor: pointer;

      &:hover {
        overflow-y: auto;
        -webkit-line-clamp: unset;
      }

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #c1c1c1;
        border-radius: 2px;
      }
    }
  }

  .difficulty-row {
    flex-shrink: 0;
    margin: 8px 0;
  }

  .tags-container {
    flex-shrink: 0;
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-bottom: 10px;

    .tag-item {
      margin: 0 !important;
    }
  }
}

.question-title {
  flex: 1;
  margin-left: 8px;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.question-checkbox {
  ::v-deep .el-checkbox__label {
    display: none;
  }

  margin-right: 0;
}

.filter-tree {
  margin-top: 10px;
  height: calc(100vh - 320px);
  overflow-y: auto;
}

.mb-20 {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}
</style>
